package com.code4j.tree;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

import com.code4j.tree.BinaryTree.Node;

public class TreeBuilder {

	//个数
	int size = 0;
	//有叶子节点的概率 3/4
	int leaf = 4;
	int num = 50;

	public TreeBuilder() {
		this(4);
	}

	public TreeBuilder(int size) {
		this.size = size;
		if (size < 1)
			throw new IllegalArgumentException("size must be > =1");
	}

	public void fillBinaryTree(BinaryTree tree) {
		Queue<Node> queue = new LinkedList<Node>();
		Random random = new Random(System.currentTimeMillis());
		int data = random.nextInt(num);
		Node root = new Node(data);
		if (tree.getRoot() == null)
			tree.setRoot(root);
		queue.offer(root);
		int in = 1;
		while (queue.size() != 0 && in <= size) {
			Node node = queue.poll();
			Node left = null;
			Node right = null;
			if (random.nextInt(leaf) != 0) {
				left = new Node(random.nextInt(num));
				node.left = left;
				queue.offer(left);
				in++;
			}
			if (random.nextInt(leaf) != 0) {
				right = new Node(random.nextInt(num));
				node.right = right;
				queue.offer(right);
				in++;
			}

		}
	}

}
